package com.zgkxzx.mvvmbase.view.activity;

import android.app.Activity;
import android.content.Context;
import android.databinding.DataBindingUtil;
import android.databinding.ViewDataBinding;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;

import com.zgkxzx.mvvmbase.viewmodel.BaseViewModel;


public abstract class BaseActivity<BV extends ViewDataBinding, VM extends BaseViewModel> extends Activity {

    private static final String TAG = BaseActivity.class.getSimpleName();
    protected Context mContext;

    protected BV viewBinding;

    protected VM viewModel;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //赋值上下文
        mContext = this;
        //绑定界面
        viewBinding = DataBindingUtil.setContentView(this, getLayoutId());
        //获取到ViewModel
        viewModel = getViewModel(mContext);
        //View 与 ViewModel绑定
        boolean status = viewBinding.setVariable(getBrId(), viewModel);
        Log.d(TAG, " binding status " + status);
        //初始化其他View
        initViews(savedInstanceState);
        //调用ViewModel onCreate 生命周期
        viewModel.onCreate();

    }

    /*
    * 获取BR Id
    * */
    protected abstract int getBrId();

    /*
    * 获取布局资源
    * */
    protected abstract int getLayoutId();

    /*
    * 获取布局资源
    * */
    protected abstract VM getViewModel(Context context);


    /*
    * 初始化视图
    * */
    protected abstract void initViews(Bundle savedInstanceState);


    @Override
    protected void onDestroy() {
        super.onDestroy();
        viewModel.onDestroy();
    }


    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK
                && event.getAction() == KeyEvent.ACTION_DOWN) {
            finish();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}